
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPFYanChatServer.Properties;
using System.Collections.ObjectModel;

namespace WPFYanChatServer
{
    /// <summary>
    /// Main.xaml 的交互逻辑
    /// </summary>
    public partial class Main : Window
    {
        // Thread signal.
        private ManualResetEvent allDone = new ManualResetEvent(false);
        private Socket listener;
        private bool m_Listening;
        public static  string ServerIP = IpConfig.getIp();
        /// <summary>
        /// 创建托盘区图标菜单项
        /// </summary>
        public  System.Windows.Forms.MenuItem[] menuItems;
        /// <summary>
        /// 创建托盘区图标实例
        /// </summary>
        public  System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();

        /// <summary>
        /// 创建托盘区图标右键菜单实例
        /// </summary>
        public  System.Windows.Forms.ContextMenu notifyIconMenu = new System.Windows.Forms.ContextMenu();

        public  string strIsFlagFlash = "N";

        /// <summary>
        /// 未登陆时的托盘区图标
        /// </summary>
        public static System.Drawing.Icon Icon_Login = WPFYanChatServer.Properties.Resources.login;

        /// <summary>
        /// 在线时的托盘区图标
        /// </summary>
        public static System.Drawing.Icon Icon_Online = WPFYanChatServer.Properties.Resources.Online;

        public static ObservableCollection<string> ListLogs = new ObservableCollection<string>();

        public Main()
        {
            InitializeComponent();
           
            try
            {

                ListLogs.Add("服务器IP" + ServerIP + ":" + IpConfig.Port);
                TBServerIP.Text = ServerIP + ":" + IpConfig.Port;
                ThreadStart myThreadDelegate = new ThreadStart(Listen);
                Thread myThread = new Thread(myThreadDelegate);
                myThread.Start();
                notifyIcon.Icon = Icon_Login;
                notifyIcon.Visible = true;
                notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseDoubleClick);
                menuItems = new System.Windows.Forms.MenuItem[1];
                menuItems[0] = new System.Windows.Forms.MenuItem();
                menuItems[0].Text = "退出";
                menuItems[0].Click += new EventHandler(notifyExit_Click);
                menuItems[0].DefaultItem = true;
                notifyIconMenu = new System.Windows.Forms.ContextMenu(menuItems);
                notifyIcon.ContextMenu = notifyIconMenu;
                items.ItemsSource = ListLogs;


            }
            catch (Exception ex)
            {
                ServerLog.writeLog("Main" + ex.Message.ToString() + DateTime.Now.ToString("yyyy-MM-dd"));
            }
        }




        private void Listen()
        {

            try
            {
                // Bind the socket to the local endpoint and listen for incoming connections.

                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), IpConfig.Port);
                listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(localEndPoint);
                listener.Listen(1000);
                m_Listening = true;
                while (m_Listening)
                {
                    // Set the event to nonsignaled state.
                    allDone.Reset();
                    // Start an asynchronous socket to listen for connections.
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), null);
                    // Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }

            }
            catch (Exception ex)
            {
                ServerLog.writeLog("Listen" + ex.Message.ToString() + DateTime.Now.ToString("yyyy-MM-dd"));
            }

        }

        public void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                // Signal the main thread to continue.
                allDone.Set();
                // Get the socket that handles the client request.
                Socket newSock = listener.EndAccept(ar);
                XmppSeverConnection con = new XmppSeverConnection(newSock);
            }
            catch (Exception ex)
            {
                ServerLog.writeLog("AcceptCallback" + ex.Message.ToString() + DateTime.Now.ToString("yyyy-MM-dd"));
            }
            //listener.BeginReceive(buffer, 0, BUFFERSIZE, 0, new AsyncCallback(ReadCallback), null);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                listener.Close();
            }
            catch (Exception ex)
            {
                ServerLog.writeLog("Window_Closed" + ex.Message.ToString() + DateTime.Now.ToString("yyyy-MM-dd"));
            }
        }





        /// <summary>
        /// 托盘区图标双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            try
            {
                //如果主窗体已在前台
                if (this.Visibility == Visibility.Visible)
                {
                    this.Hide();
                }
                else
                {
                    this.Show();
                    this.Activate();
                    this.Topmost = true;
                }

            }
            catch
            {
            }
        }


        /// <summary>
        /// 单击托盘区“退出”菜单事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void notifyExit_Click(object sender, EventArgs e)
        {
            try
            {
                m_Listening = false;
                this.Close();
            }
            catch (Exception ex)
            {
                ServerLog.writeLog("notifyExit_Click" + ex.Message.ToString() + DateTime.Now.ToString("yyyy-MM-dd"));
            }
         
        }
    }


}
